package com.evan.review.ipc;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Process;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * AIDL通信示例
 * 演示如何使用AIDL进行跨进程通信
 */
public class AIDLDemoActivity extends AppCompatActivity {
    private static final String TAG = "AIDLDemoActivity";
    
    private TextView tvStatus;
    private TextView tvCallbackMessages;
    private EditText etMessage;
    private Button btnBindService;
    private Button btnUnbindService;
    private Button btnGetPid;
    private Button btnGetMessage;
    private Button btnSendMessage;
    private Button btnShowAidlInfo;
    
    // 远程服务接口
    private IRemoteService remoteService;
    // 是否已绑定服务
    private boolean isBound = false;
    // 消息ID计数器
    private final AtomicInteger messageIdCounter = new AtomicInteger(1);
    // 主线程Handler
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidl_demo);
        
        // 初始化视图
        initViews();
        // 设置点击监听
        setupListeners();
        
        updateStatus("当前进程ID: " + Process.myPid());
    }
    
    private void initViews() {
        tvStatus = findViewById(R.id.tv_aidl_status);
        tvCallbackMessages = findViewById(R.id.tv_callback_messages);
        etMessage = findViewById(R.id.et_aidl_message);
        btnBindService = findViewById(R.id.btn_bind_service);
        btnUnbindService = findViewById(R.id.btn_unbind_service);
        btnGetPid = findViewById(R.id.btn_get_pid);
        btnGetMessage = findViewById(R.id.btn_get_message);
        btnSendMessage = findViewById(R.id.btn_send_message);
        btnShowAidlInfo = findViewById(R.id.btn_aidl_info);
        
        // 初始状态下禁用需要服务连接的按钮
        setButtonsEnabled(false);
    }
    
    private void setupListeners() {
        // 绑定服务
        btnBindService.setOnClickListener(v -> bindRemoteService());
        
        // 解绑服务
        btnUnbindService.setOnClickListener(v -> unbindRemoteService());
        
        // 获取远程进程ID
        btnGetPid.setOnClickListener(v -> {
            if (isServiceReady()) {
                try {
                    int pid = remoteService.getPid();
                    updateStatus("远程服务进程ID: " + pid);
                } catch (RemoteException e) {
                    handleRemoteException(e);
                }
            }
        });
        
        // 获取远程消息
        btnGetMessage.setOnClickListener(v -> {
            if (isServiceReady()) {
                try {
                    String message = remoteService.getMessage("Hello from client");
                    updateStatus("收到远程消息: " + message);
                } catch (RemoteException e) {
                    handleRemoteException(e);
                }
            }
        });
        
        // 发送消息对象
        btnSendMessage.setOnClickListener(v -> {
            if (isServiceReady()) {
                try {
                    String content = etMessage.getText().toString();
                    if (content.isEmpty()) {
                        content = "测试消息 #" + messageIdCounter.get();
                    }
                    
                    MessageParcel message = new MessageParcel(
                            messageIdCounter.getAndIncrement(),
                            content,
                            Process.myPid()
                    );
                    
                    updateStatus("发送消息: " + message);
                    MessageParcel response = remoteService.sendMessage(message);
                    updateStatus("收到响应: " + response);
                    
                    // 清空输入框
                    etMessage.setText("");
                } catch (RemoteException e) {
                    handleRemoteException(e);
                }
            }
        });
        
        // 显示AIDL信息
        btnShowAidlInfo.setOnClickListener(v -> showAidlInfo());
    }
    
    /**
     * 绑定远程服务
     */
    private void bindRemoteService() {
        Intent intent = new Intent(this, RemoteService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
        updateStatus("正在绑定远程服务...");
    }
    
    /**
     * 解绑远程服务
     */
    private void unbindRemoteService() {
        if (isBound) {
            // 解注册回调
            if (remoteService != null) {
                try {
                    remoteService.unregisterCallback(remoteCallback);
                } catch (RemoteException e) {
                    Log.e(TAG, "解注册回调失败: " + e.getMessage());
                }
            }
            
            // 解绑服务
            unbindService(serviceConnection);
            isBound = false;
            remoteService = null;
            
            // 更新UI
            updateStatus("已解绑远程服务");
            setButtonsEnabled(false);
        }
    }
    
    /**
     * 服务连接回调
     */
    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 获取远程服务接口
            remoteService = IRemoteService.Stub.asInterface(service);
            isBound = true;
            
            // 注册回调
            try {
                remoteService.registerCallback(remoteCallback);
                updateStatus("已连接到远程服务");
                setButtonsEnabled(true);
            } catch (RemoteException e) {
                handleRemoteException(e);
            }
        }
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 服务意外断开
            remoteService = null;
            isBound = false;
            updateStatus("远程服务已断开");
            setButtonsEnabled(false);
        }
    };
    
    /**
     * 远程回调实现
     */
    private final IRemoteCallback remoteCallback = new IRemoteCallback.Stub() {
        @Override
        public void onMessageReceived(String message) {
            // 在主线程更新UI
            mainHandler.post(() -> {
                String currentText = tvCallbackMessages.getText().toString();
                tvCallbackMessages.setText(currentText + "\n" + message);
            });
        }
        
        @Override
        public void onParcelReceived(MessageParcel parcel) {
            mainHandler.post(() -> {
                String currentText = tvCallbackMessages.getText().toString();
                tvCallbackMessages.setText(currentText + "\n收到对象: " + parcel.toString());
            });
        }
    };
    
    /**
     * 检查服务是否已准备好
     */
    private boolean isServiceReady() {
        if (!isBound || remoteService == null) {
            Toast.makeText(this, "服务未连接，请先绑定服务", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
    
    /**
     * 处理远程调用异常
     */
    private void handleRemoteException(RemoteException e) {
        Log.e(TAG, "远程调用异常: " + e.getMessage());
        updateStatus("远程调用失败: " + e.getMessage());
        
        // 服务可能已死亡，重置状态
        if (e instanceof android.os.DeadObjectException) {
            isBound = false;
            remoteService = null;
            setButtonsEnabled(false);
        }
    }
    
    /**
     * 更新状态显示
     */
    private void updateStatus(String status) {
        String currentStatus = tvStatus.getText().toString();
        tvStatus.setText(currentStatus + "\n" + status);
    }
    
    /**
     * 设置按钮启用状态
     */
    private void setButtonsEnabled(boolean enabled) {
        btnUnbindService.setEnabled(enabled);
        btnGetPid.setEnabled(enabled);
        btnGetMessage.setEnabled(enabled);
        btnSendMessage.setEnabled(enabled);
        btnBindService.setEnabled(!enabled);
    }
    
    /**
     * 显示AIDL信息对话框
     */
    private void showAidlInfo() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("AIDL通信介绍")
                .setMessage("AIDL (Android Interface Definition Language) 是Android提供的一种IPC机制。\n\n" +
                        "主要特点：\n" +
                        "1. 支持复杂接口定义和自定义数据类型传递\n" +
                        "2. 支持客户端-服务器模式的方法调用\n" +
                        "3. 支持并发访问和回调机制\n\n" +
                        "使用步骤：\n" +
                        "1. 定义.aidl接口文件\n" +
                        "2. 实现服务端接口\n" +
                        "3. 客户端绑定服务并调用方法\n\n" +
                        "适用场景：\n" +
                        "- 需要跨进程调用复杂接口\n" +
                        "- 需要传递自定义数据类型\n" +
                        "- 需要处理并发请求")
                .setPositiveButton("了解", null)
                .show();
    }
    
    @Override
    protected void onDestroy() {
        unbindRemoteService();
        super.onDestroy();
    }
}